<?php

namespace App\Trip\Tencent\Cloud\SDK\TCCC;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use TencentCloud\Ccc\V20200210\CccClient;
use TencentCloud\Ccc\V20200210\Models\CreateAutoCalloutTaskRequest;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;

class Tccc
{
    private string $secret_id;
    private string $secret_key;
    /**
     * @var string[]
     */
    private array  $default_callres;
    private string $sdk_appid;

    public function __construct()
    {
        $this->secret_id       = config('qcloud.secret_id');
        $this->secret_key      = config('qcloud.secret_key');
        $this->sdk_appid       = config('qcloud.tccc.sdk_appid');
        $this->default_callres = config('qcloud.tccc.default_callers');
    }

    function createAutoCalloutTask(array $param)
    {
        $business_id = $param['business_id'];
        $mobile      = $param['mobile'];
        $callees     = $this->getMobiles($mobile);
        try {
            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            $cred = new Credential($this->secret_id, $this->secret_key);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("ccc.tencentcloudapi.com");

            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            $client = new CccClient($cred, "", $clientProfile);

            // 实例化一个请求对象,每个接口都会对应一个request对象
            $req = new CreateAutoCalloutTaskRequest();

            $params = [
                "SdkAppId"  => (int)$this->sdk_appid,
                "NotBefore" => 5,
                "Callees"   => $callees,
                "Callers"   => $this->default_callres,
                "IvrId"     => $business_id,
            ];

            $req->fromJsonString(json_encode($params));

            // 返回的resp是一个CreateAutoCalloutTaskResponse的实例，与请求对象对应
            $resp = $client->CreateAutoCalloutTask($req);

            // 输出json格式的字符串回包
            return $resp->toJsonString();
        } catch (TencentCloudSDKException $e) {
            Log::error("腾讯云tccc业务异常,".$e->getMessage());
        }
    }

    private function getMobiles($mobile): array
    {
        $res = [];
        if (is_array($mobile)) {
            $res = $mobile;
        } else {
            $res[] = $mobile;
        }
        return collect($res)->map(function ($mb) {
            $prefix = "0086";
            return $prefix.Str::replaceFirst($prefix, "", $mb);

        })->toArray();
    }
}